//
//  Date+Entension.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/8.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import Foundation

extension Date {
    var weiboConposeDate:String? {
        let dateFormatter = DateFormatter()
        // 如果是今年
        if isThisYear(createTime: self) {
            // 如果是今天或者昨天
            let calendar = Calendar.current
            if calendar.isDateInToday(self) {
                
                let timeInterval = abs(self.timeIntervalSinceNow)
                if timeInterval < 60 {
                    return "刚刚"
                }else if timeInterval < 3600 {
                    return "\(Int(timeInterval) / 60)分钟前"
                }else {
                    return "\(Int(timeInterval) / 3600)小时前"
                }
                
                
            }else if calendar.isDateInYesterday(self) {
                // 如果不是:昨天 HH:mm
                dateFormatter.dateFormat = "昨天 HH:mm"
                
            }else {
                // 如果不是:MM-DD
                dateFormatter.dateFormat = "MM-dd HH:mm"
                
            }
            
        }else {
            // 如果不是今年:YY-MM-DD
            dateFormatter.dateFormat = "YY-MM-DD"
            
            
        }
        
        
        return dateFormatter.string(from: self)
    }
    
    private func isThisYear (createTime:Date)->(Bool) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY"
        
        let createYear = dateFormatter.string(from: createTime)
        let currentYear = dateFormatter.string(from: Date())
        
        return createYear == currentYear
        
    }

    
}
